<!-- pagedetail -->
<template>
	<div class="bg">
		<goback></goback>


		<div class="card">
			<div class="card_title">
				<div class="card_title_context">{{page.title}}</div>
				<div class="card_title_author">作者：{{page.author}}</div>
				<div class="card_title_bottom">
					<div class="card_title_bottom_date">{{formatDate(page.timestamp)}}</div>
					<div class="card_title_bottom_read">阅读 {{page.hot}}</div>
				</div>
			</div>
			<div class="card_imgs_box" ref="cardImgsBox">
				<div class="card_img" v-for="(item, index) in page.imgs" :key="index">
					<img :src="getSrc(index)" alt="Image" />
				</div>
			</div>
			<div class="card_container">
				<div class="card_context_everyParagraph" v-for="(item,index) in page.content">
					{{item}}
					<img :src="require(`@/assets/icons/播放中.png`)" v-if="page.voice_start[index] == true"
						@click="toVoice(item,index)" />
					<img :src="require(`@/assets/icons/播放.png`)" v-else @click="toVoice(item,index)" />
				</div>
			</div>
			<div class="card_icons">
				<img :src="require(`@/assets/icons/复制.png`)" alt="Image" @click="copyTextToClipboard" />
				<img :src="require(`@/assets/icons/分享.png`)" alt="Image" @click="copyCurrentPageUrl" />
			</div>

			<div class="card_context">
				<div v-for="(tag,tagindex) in page.tags">{{tag}}</div>

			</div>

		</div>


		<div class="card">
			<div class="card_title">评论</div>
			<div class="comment_box" v-for="(item,index) in page.replies">
				<div class="comment_img" @click="gotoUserPage(item.replyuid)">
					<img :src="getHeadSrc(item.replyuid)" alt="" />
				</div>
				<div class="comment_innerbox">
					<div class="comment_user_box">
						<div>{{userNamesCache[item.replyuid]}}</div>
						<div>{{formatDate(item.timestamp)}}</div>
					</div>
					<div class="comment_context">
						{{item.content}}
					</div>
					<div class="comment_icons">

						<div class="likes_container">
							<img v-if="item.has_liked" :src="require(`@/assets/icons/点赞 (1).svg`)" alt=""
								@click="send_like(item.replyid)" />
							<img v-else :src="require(`@/assets/icons/点赞.svg`)" alt=""
								@click="send_like(item.replyid)" />
							<div>{{item.like}}</div>
						</div>

						<div class="likes_container">
							<img @click="toggleccTwiceCommend(index)" :src="require(`@/assets/icons/评论.png`)" alt="" />
							<div>{{item.replies.length}}</div>
						</div>

					</div>
					<div class="reply_box">
						<div class="reply_every" v-for="(temp,tempindex) in item.replies">
							<div @click="gotoUserPage(temp.replyuid)">{{userNamesCache[temp.replyuid]}} :</div>
							<div>{{temp.content}}</div>
						</div>
						<div class="reply_every want_to_say" v-if="item.user_want_to_say">
							<input placeholder="请输入您想回复的内容..." v-model="want_to_reply"></input>
							<button @click="send_reply(item.replyid)">回复</button>
						</div>

					</div>
				</div>
			</div>
		</div>

		<div class="send_comment_box">
			<input class="send_comment_box_input" ref="inputField" @blur="handleBlur" v-model="now_message"
				placeholder="请输入您想发表的内容"></input>
			<MyEmojis @select="onEmojiSelect"></MyEmojis>
			<button class="send_comment_box_button" @click="send_commend">发表</button>
		</div>

		<div class="placeblock"></div>
	</div>

</template>

<script>
	import {
		compile
	} from 'vue-template-compiler';
	export default {
		name: "pages",
		components: {

		},
		data() {
			return {

				pageID: 0,
				page: {

				},
				want_to_reply: '',
				userNamesCache: {},
				now_message: '',
				audioElement: null, // 用于存储Audio对象  
			};
		},

		methods: {
			toVoice(context, index) {
				if (this.page.voice_start[index] == false) {
					this.axios.get(`${this.IP}/text_to_voice`, {
							responseType: 'blob', // 告诉axios期望服务器响应的数据类型为blob  
							params: {
								text: context
							}
						}).then(response => {
							// 创建Blob对象  
							const blob = new Blob([response.data], {
								type: 'audio/mpeg'
							}); // 假设返回的是MP3格式的音频  
							// 创建一个指向该Blob对象的URL  
							const audioUrl = URL.createObjectURL(blob);

							// 创建一个audio元素并设置其src属性为上面创建的URL  
							this.audioElement = new Audio(audioUrl);
							// 播放音频  
							this.audioElement.play();

							// 当音频播放结束时，释放URL对象  
							this.audioElement.addEventListener('ended', () => {
								URL.revokeObjectURL(audioUrl);
								this.page.voice_start[index] = !this.page.voice_start[index];
							});

							console.log('Audio playback started.');
						})
						.catch(error => {
							console.error('Error fetching audio:', error);
						});
				} else {
					this.audioElement.pause();
				}
				this.page.voice_start[index] = !this.page.voice_start[index]
				this.$forceUpdate();
			},

			getAllName() {
				this.page.replies.forEach((e) => {
					this.axios.get(`${this.IP}/getUserByUID`, {
						params: {
							uid: e.replyuid
						}
					}).then(res => {
						this.userNamesCache[e.replyuid] = res.data.name;
						this.$forceUpdate();



						e.replies.forEach((d) => {
							this.axios.get(`${this.IP}/getUserByUID`, {
								params: {
									uid: d.replyuid
								}
							}).then(res2 => {
								console.log(res2);
								this.userNamesCache[d.replyuid] = res2.data.name;
								this.$forceUpdate();
							})
						})





					}).catch(error => {
						console.error('Error loading user names:', error);
					});;
				})
			},
			send_like(i) {
				console.log(i);
				this.axios.get(`${this.IP}/toggle_like`, {
					params: {
						id: this.pageID,
						token: this.getStorage('token'),
						replyid: i
					}
				}).then(res => {
					console.log(res)
					this.$toast.showMessage(res.data);
					this.like()


				}).catch(error => {
					console.error('Error loading user names:', error);
				});;
			},
			like() {
				this.axios.get(`${this.IP}/get_page`, {
					params: {
						id: this.pageID,
						token: this.getStorage('token')
					}
				}).then(res => {
					this.page = res.data;

				})

			},
			gotoUserPage(e) {
				this.$router.push(`/userInfo?uid=` + e);
			},
			getHeadSrc(e) {
				return `${this.IP}/img/${e}.jpg`;
			},
			formatDate(timestamp) {
				const date = new Date(timestamp); // JavaScript时间戳是以毫秒为单位的，所以需要乘以1000  
				const year = date.getFullYear();
				const month = this.padZero(date.getMonth() + 1); // getMonth()返回的月份是从0开始的，所以需要加1  
				const day = this.padZero(date.getDate());
				const hour = this.padZero(date.getHours());
				const minutes = this.padZero(date.getMinutes());
				return `${year}年${month}月${day}日  ${hour}:${minutes}`;
			},
			padZero(num) {
				return num < 10 ? '0' + num : num;
			},
			getSrc(i) {
				return `${this.IP}/pages_image/${this.pageID}/${i}.jpg`
			},
			getPage() {

				if (this.getStorage('token') == null) {
					this.axios.get(`${this.IP}/get_page`, {
							params: {
								id: this.pageID,

							}
						}).then(res => {
							this.page = res.data;
							this.page.replies.forEach((e) => {
								e.user_want_to_say = false;
							})
							this.getAllName();

							let voice_arr = new Array();
							this.page.content.forEach(e => {
								voice_arr.push(false);
							})
							this.page.voice_start = voice_arr;


						})
						.catch(error => {
							console.error(error);
						});
				} else {
					this.axios.get(`${this.IP}/get_page`, {
							params: {
								id: this.pageID,
								token: this.getStorage('token')
							}
						}).then(res => {
							this.page = res.data;
							this.page.replies.forEach((e) => {
								e.user_want_to_say = false;
							})
							this.getAllName();
							console.log(this.page);

							let voice_arr = new Array();
							this.page.content.forEach(e => {
								voice_arr.push(false);
							})
							this.page.voice_start = voice_arr;


						})
						.catch(error => {
							console.error(error);
						});
				}






			},
			handleBlur() {
				this.caretPosition = {
					start: this.$refs.inputField.selectionStart,
					end: this.$refs.inputField.selectionEnd,
				};

			},
			onEmojiSelect(emoji) {
				// 当Emoji被选中时，将其添加到message中  
				if (this.caretPosition != null && this.caretPosition.start != null) {
					this.now_message = this.now_message.slice(0, this.caretPosition.start) + emoji + this.now_message
						.slice(
							this.caretPosition.start, this.now_message.length)
				} else {
					this.now_message = this.now_message + emoji;
				}

			},
			toggleccTwiceCommend(index) {

				this.page.replies[index].user_want_to_say = !this.page.replies[index].user_want_to_say;
				console.log(this.page);
				this.$forceUpdate();
			},
			send_reply(id) {
				this.axios.get(`${this.IP}/send_reply`, {
					params: {
						token: this.getStorage('token'),
						content: this.want_to_reply,
						id: this.$route.query.pageID,
						replyid: id
					}
				}).then(res => {
					this.want_to_reply = "";
					this.$toast.showMessage(res.data);
					setTimeout(function() {
						location.reload();
					}, 1000)
				}).catch(error => {
					this.$toast.showMessage(error);
				});;


			},
			send_commend() {
				this.axios.get(`${this.IP}/send_comment`, {
					params: {
						token: this.getStorage('token'),
						content: this.now_message,
						id: this.$route.query.pageID
					}
				}).then(res => {
					this.$toast.showMessage(res.data);
					setTimeout(function() {
						location.reload();
					}, 1000)
				}).catch(error => {
					this.$toast.showMessage(error);
				});;
			},
			copyTextToClipboard() {
				if (!navigator.clipboard) {
					this.$toast.showMessage('您的浏览器不支持剪贴板操作');
					return;
				}

				const textToCopy = this.page.content;

				if (!textToCopy) {
					this.$toast.showMessage('没有内容可供复制');
					return;
				}

				navigator.clipboard.writeText(textToCopy)
					.then(() => {
						this.$toast.showMessage('文章已成功复制到剪贴板');
					})
					.catch(err => {
						console.error('无法复制文本: ', err);
						this.$toast.showMessage('复制文本时出错，请检查您的浏览器或稍后重试');
					});
			},

			copyCurrentPageUrl() {
				// 获取当前页面的完整URL  
				const currentPageUrl = window.location.href;
				if (navigator.clipboard) {
					navigator.clipboard.writeText('发现了一篇很好看的文章！' + currentPageUrl)
						.then(() => {
							this.$toast.showMessage('页面链接已复制到剪贴板，您可以粘贴分享了！');
						})
						.catch(err => {
							console.error('无法复制文本: ', err);
							this.$toast.showMessage('复制页面链接时出错，请检查您的浏览器或稍后重试');
						});
				} else {
					this.$toast.showMessage('您的浏览器不支持剪贴板操作，请手动复制页面链接。');
				}
			}
		},
		mounted() {
			this.pageID = this.$route.query.pageID;
			this.getPage();
		}
	};
</script>

<style scoped>
	.card_context_everyParagraph {
		position: relative;
	}

	.card_context_everyParagraph img {
		position: absolute;
		right: 30px;
		bottom: 15px;
		width: 38px;
	}

	.card_title {
		display: flex;
		flex-direction: column;
	}

	.card_title_context {
		font-size: 32px;
		padding: 1vw;

	}

	.card_title_author {
		color: #d5d5d5;
		margin-left: 1vw;
		margin-top: 1vw;
		margin-bottom: 1vw;
	}

	.card_title_bottom {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		color: #d5d5d5;
	}

	.card_context_everyParagraph {
		text-indent: 2em;
		padding: 3vw;
		margin: 3vw auto;
		max-width: 78vw;
		border-radius: 20px;
		word-wrap: break-word;
		background-color: #ebebeb;
		font-size: 28px;
	}

	.card_imgs_box {
		width: 83vw;
		margin: 0 auto;
		height: 25vw;
		overflow-x: auto;
		scroll-snap-type: x mandatory;
		scroll-padding: 20px;
		/* 为第一张图片预留一些空间，确保不会一开始就被隐藏 */
		scroll-snap-align: start;
		border: 1px solid #ebebeb;
		border-radius: 20px;
		display: flex;
		align-items: center;
	}


	.card_img {
		width: 23vw;
		height: 23vw;
		flex: 0 0 20vw;
		/* 固定宽度，防止收缩 */
		margin-right: 6px;
		scroll-snap-align: start;

	}

	.card_img:last-child {
		margin-right: 0;
	}

	.card_img img {
		width: 100%;
		height: 100%;
		object-fit: cover;
		/* 确保图片覆盖整个容器 */
	}

	.card_icons {
		display: flex;
		justify-content: flex-end;
		flex-direction: row;
		padding: 2vw;
	}

	.card_icons img {
		width: 32px;
		height: 32px;
		padding: 1vw;
	}

	.comment_box {
		display: flex;
		flex-direction: row;
		border-bottom: 1px solid #ebebeb;
		padding: 2vw 1vw 1vw 0vw;
	}

	.likes_container {
		display: flex;
		flex-direction: row;
		margin: 0vw 2vw 0vw 0vw;
	}

	.likes_container img {
		margin-right: 3px;
	}

	.comment_img {
		width: 12vw;
		height: 100%;
	}

	.comment_img img {
		width: 12vw;
		height: 12vw;
		border-radius: 50%;
	}

	.comment_innerbox {
		display: flex;
		flex-direction: column;
		margin: 1vw;
	}

	.comment_user_box {
		display: flex;
		flex-direction: column;
	}

	.comment_user_box div:nth-child(1) {
		font-size: 26px;
		color: #333;
	}

	.comment_user_box div:nth-child(2) {
		font-size: 20px;
		color: #999;
	}

	.comment_context {
		margin-top: 10px;
		font-size: 26px;
	}

	.comment_icons {
		display: flex;
		justify-content: flex-start;
		padding-top: 1vw;
		align-items: center;
		box-sizing: border-box;
	}

	.comment_icons img {
		width: 32px;
	}

	.reply_box {
		width: 70vw;
		height: auto;
		display: flex;
		flex-direction: column;
		background-color: #dbdbdb;
		border-radius: 10px;
		margin-top: 1vw;
	}

	.reply_every {
		display: flex;
		flex-direction: row;
		padding: 1vw;
		border-bottom: 1px solid #eeeeee;
	}

	.reply_every div:nth-child(1) {
		color: darkblue;
		max-width: 20vw;
		overflow: hidden;
		/* 隐藏超出元素框的内容 */
		text-overflow: ellipsis;
		/* 当内容溢出时，显示省略号 (...) */
		white-space: nowrap;
		/* 防止文本换行 */


	}

	.want_to_say {
		display: flex;
		justify-content: flex-end;
	}

	.want_to_say input {
		width: 75%;
		padding: 1vw;
		margin-right: 1vw;
		border-radius: 20px;
	}

	.want_to_say button {
		width: 20%;
		border-radius: 20px;
		padding: 1vw;
	}

	.send_comment_box {
		z-index: 10;
		position: fixed;
		bottom: 0px;
		width: 100vw;
		height: 10vw;
		display: flex;
		flex-direction: row;
		background-color: #fff;
		padding: 1vw;
		box-sizing: border-box;
		vertical-align: middle;
	}

	.send_comment_box_button {
		width: 12vw;
		border-radius: 20px;
	}

	.send_comment_box_input {
		background-color: #dbdbdb;
		border-radius: 20px;
		flex: 1;
		padding: 2vw;
		vertical-align: middle;
		max-height: 5vw;
	}
</style>